package util.fileUtil;

import android.content.Context;
import android.widget.Toast;
import com.example.administrator.text.R;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import app.MyApplication;
import data.SharedPreferencesUtils;
import de.mindpipe.android.logging.log4j.LogConfigurator;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.LogUtil;
import util.NetWorkstateUtil;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import util.getInformation;
import util.listComparator.FileComparator;
import view.diaLogView.UploadDialog;

/**
 * log日志选择最后两个要上传的日志文件
 */
public class SelectFiles {
    private static final int UPLOAD_NUMBER = 2;          //上传文件的数量
    private ArrayList<FileInfo> mFileList;              //得到所以文件
    private ArrayList<FileInfo> mSelectLastTwoFilsList;//需要上传的文件
    private static SelectFiles mSelectFiles;
    private LogConfigurator mLogConfigurator;         //日志对象
    private int mCode;                               //记录服务器的信息Code
    private Logger mLogger = Logger.getLogger(SelectFiles.class);
    private UploadDialog mUploadDialog;
    private String mUrlString;
    public static synchronized SelectFiles getNewSelectFiles(){

        if (mSelectFiles == null){
            mSelectFiles = new SelectFiles();
            return mSelectFiles;
        }
        return mSelectFiles;
    }

    /**
     * @param parentFilePath 父目录
     *此方法主要将父目录下的文件按时间进行排序,从远到近
     */
    public void sortFiles(String parentFilePath) {
        File parentFile = new File(parentFilePath);
        File fatherFile = new File(parentFile.getParent());//得到父目录的路径
        if (fatherFile.exists()) {
            File[] files = fatherFile.listFiles(); //通过listFiles可以列出所有所有文件
            LogUtil.eE("File","  "+files.length);
            //将需要的子文件信息存入到FileInfo里面
            mFileList = new ArrayList<FileInfo>();
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                FileInfo fileInfo = new FileInfo();
                fileInfo.name = file.getName();
                fileInfo.path = file.getPath();
                fileInfo.lastModified = file.lastModified();
                mFileList.add(fileInfo);
            }

            Collections.sort(mFileList, new FileComparator());//对指定的List列表进行升序或降序
        }
    }

    /**
     * @param parentFilePath 父目录
     *选取最后访问时间两个文件
     */
    private ArrayList<FileInfo> selectLastTwoFils(String parentFilePath,int selectFilesCount) {
        sortFiles(parentFilePath);
        mSelectLastTwoFilsList = new ArrayList<>();
        LogUtil.eE("File","  "+mFileList.size());
        if (mFileList.size() > 0) {
            for (int fileListSize = mFileList.size() - 1; fileListSize >= 0; fileListSize--) {
                if ((mFileList.size() - fileListSize - 1) == selectFilesCount) {
                    break;
                }
                mSelectLastTwoFilsList.add(mFileList.get(fileListSize));
            }
        }
        return mSelectLastTwoFilsList;
    }

    /**
     * 得到压缩文件
     *
     * @param srcDic   需要压缩的文件目录
     * @param destFile 压缩到目的文件
     * @throws IOException 抛出异常
     */
    public void getZipFile(String srcDic, File destFile) throws IOException {
        selectLastTwoFils(srcDic, 2);
        ArrayList<File> zipfileList = new ArrayList<>();
        for (int i = 0; i < mSelectLastTwoFilsList.size(); i++) {
            zipfileList.add(new File(mSelectLastTwoFilsList.get(i).path));
        }
        //压缩目的文件
        if (destFile.exists()) {
            ZipUtils.getmZipUtils().zipFiles(zipfileList, destFile, "");
        }
    }

    /**
     *日志文件上传
     * @param context 上下文
     * @throws IOException 异常
     */
    public void getFileUpload(final Context context, final String fwq) throws IOException {
        File file;
        String fwq1;
        mLogConfigurator = MyApplication.getApp().getLogConfigurator();
        String id = (String) SharedPreferencesUtils.getParam(context, HomeUtil.mUseridDB,"");
        String fileString = mLogConfigurator.getFileName();
        mUploadDialog = new UploadDialog(context,context.getString(R.string.tv_uoload));
        mUploadDialog.show();
        selectLastTwoFils(fileString,UPLOAD_NUMBER);
        if(mSelectLastTwoFilsList.size() == 0) {
            Toast.makeText(context,"目前没有日志文件",Toast.LENGTH_SHORT).show();
            mUploadDialog.dismiss();
            return;
        }

        Map<String,Object> map = new HashMap<>();
         for (int i = 0; i < mSelectLastTwoFilsList.size(); i++) {
             file = new File(mSelectLastTwoFilsList.get(i).path);
             map.put("file"+(i+1),file);
             mLogger.info("getFileUpload()--->日志上传---文件大小---"+file.length());
         }
        LogUtil.eE("","........fwq..........."+fwq);
        if(fwq.equals("http://119.29.54.250:8090")){
             fwq1 = fwq.substring(0,fwq.length()-4)+"8090";
        }else {
             fwq1 = fwq.substring(0,fwq.length()-4)+"8080";
        }

        mLogger.info("getFileUpload()--->日志上传开始---fwq1"+fwq1 + Url.UPLOAD_LOG);
        map.put("userid",id);
        map.put("deviceType",getInformation.getNewGetInformation(context).getInfoPhoneType());
        map.put("phone",SharedPreferencesUtils.getParam(context, HomeUtil.mHUWePhone,""));
        map.put("areaid",MyApplication.getApp().getSiteAreaid()+"");
        GreenTreeNetworkUtil.getInstance().doPostFile(fwq1 + Url.UPLOAD_LOG,map,new RequestDataCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    mCode = jsonObject.getInt("code");
                    mLogger.info("getFileUpload()--->日志上传结束---String"+response);
                    mUploadDialog.dismiss();
                    brokenNetwork(context);
                    if(mCode == 1){
                        Toast.makeText(context, context.getString(R.string.upload_yes), Toast.LENGTH_SHORT).show();
                        mSelectFiles.clone();
                        mSelectLastTwoFilsList.clear();
                    }else { Toast.makeText(context, context.getString(R.string.uplod_no), Toast.LENGTH_SHORT).show();}

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Throwable error) {
                brokenNetwork(context);
                mUploadDialog.dismiss();
                StringUtil.getStringUtilNew().getExceptionCode(context,error.toString());
            }
        });
    }

    private void brokenNetwork(Context context){
        if(Url.getUrlNew().getNETWORKING_ATATE() == 1){
            NetWorkstateUtil.getInstance().getBrokenNetwork(context, new HomeUtil.OnHomeUtilClickListener() {
                @Override
                public void onItemClick(String type) {
                            if(type.equals("ok")){
                                Url.getUrlNew().setNETWORKING_ATATE(0);
                            }
                }
            }, 1);
        }
    }

    /**
     *日志文件上传
     * @param context 上下文
     * @throws IOException 异常
     */
    public void getFileLogUpload(final Context context, final String fwq) throws IOException {
        File file;
        mLogConfigurator = MyApplication.getApp().getLogConfigurator();
        String id = (String) SharedPreferencesUtils.getParam(context, HomeUtil.mUseridDB,"");
        String fileString = mLogConfigurator.getFileName();
        selectLastTwoFils(fileString,1);
        if(mSelectLastTwoFilsList.size() == 0) {
            Toast.makeText(context,"目前没有日志文件",Toast.LENGTH_SHORT).show();
            mUploadDialog.dismiss();
            return;
        }
        Map<String,Object> map = new HashMap<>();
        for (int i = 0; i < mSelectLastTwoFilsList.size(); i++) {
            file = new File(mSelectLastTwoFilsList.get(i).path);
            map.put("file"+(i+1),file);
            LogUtil.eE("","........................"+i);
        }

        map.put("userid",id);
        map.put("deviceType",getInformation.getNewGetInformation(context).getInfoPhoneType());
        map.put("phone",SharedPreferencesUtils.getParam(context, HomeUtil.mHUWePhone,""));
        map.put("areaid",MyApplication.getApp().getSiteAreaid()+"");
        mUrlString = StringUtil.getStringUtilNew().getFeq(fwq,"LOGServlet");
        mLogger.info("getFileUpload()--->日志上传开始---UrlString"+mUrlString);
        GreenTreeNetworkUtil.getInstance().doPostFile(mUrlString,map,new RequestDataCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    mCode = jsonObject.getInt("code");
                    LogUtil.eE("","......"+response);
                    mLogger.info("getFileUpload()--->日志上传结束---String"+response);
                    if(mCode == 1){
                        mSelectFiles.clone();
                        mSelectLastTwoFilsList.clear();
                    }

                } catch (Exception e) {e.printStackTrace();}
            }
            @Override
            public void onFailure(Throwable error) {
                LogUtil.eE("","......Throwable"+error.toString());
                StringUtil.getStringUtilNew().getExceptionCode(context,error.toString());
            }
        });
    }
}
